package net.alpcontrol.bi.colligation.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import cn.hutool.poi.excel.ExcelUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import net.alpcontrol.bi.bootstrap.utils.ExcelUtils;
import net.alpcontrol.bi.colligation.entity.*;
import net.alpcontrol.bi.colligation.mapper.*;
import net.alpcontrol.bi.colligation.service.IPfProfitService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 丛庆
 * @since 2020-08-31
 */
@Service
@Transactional
public class PfProfitServiceImpl extends ServiceImpl<PfProfitMapper, PfProfit> implements IPfProfitService {

    @Autowired
    private PfProfitMapper pfProfitMapper;
    @Autowired
    private PfCostMapper pfCostMapper;
    @Autowired
    private PfExpenseMapper pfExpenseMapper;
    @Autowired
    private PfIncomeMapper pfIncomeMapper;
    @Autowired
    private PfOrderMapper pfOrderMapper;
    @Autowired
    private PfSalesBackMapper pfSalesBackMapper;


    /**
      *  分页查询
      * @param bootStrapTable
      * @param pfProfit
      * @return
      */
    @Override
    public IPage<PfProfit> selectPage(Page<PfProfit> page) {
        return pfProfitMapper.selectPage(page,null);
    }

    /**
     * 根据年份查询收入、利润、回款、费用、合同、成本的预算值
     *
     * @param year
     * @return
     */
    @Override
    public List<Map> getBudgetByYear(String year,String companyId) {
        List<Map> result = new ArrayList<>();
        Map<String,String> parameter = new HashMap<>();
        parameter.put("year",year);
        parameter.put("companyId",companyId);
        result.add(handleBudgetsResult("利润",pfProfitMapper.getBudgetsByYearAndCompany(parameter)));
        result.add(handleBudgetsResult("合同",pfOrderMapper.getBudgetsByYearAndCompany(parameter)));
        result.add(handleBudgetsResult("回款",pfSalesBackMapper.getBudgetsByYearAndCompany(parameter)));
        result.add(handleBudgetsResult("费用",pfExpenseMapper.getBudgetsByYearAndCompany(parameter)));
        result.add(handleBudgetsResult("主营业务成本",pfCostMapper.getBudgetsByYearAndCompany(parameter)));
        result.add(handleBudgetsResult("主营业务收入",pfIncomeMapper.getBudgetsByYearAndCompany(parameter)));
        return result;
    }

    Map handleBudgetsResult(String kpiName,List<Map> budgetList){
        Map resMap = new HashMap();
        resMap.put("kpiName",kpiName);
        for (Map profitMap:budgetList) {
            resMap.put(profitMap.get("month"),profitMap.get("budget"));
        }
        return resMap;
    }


    /**
     * 导入年度预算值
     *
     * @param file
     * @param year
     * @param companyId
     * @return
     */
    @Override
    public List<Map> importBudgets(MultipartFile file, String year, String companyId) throws Exception {
        // 没有使用实体类注解的形式，这里用的Map
        ImportParams params = new ImportParams();
        params.setTitleRows(1);//标题的行数
        params.setHeadRows(1);//表头的行数
        params.setReadRows(5);//读取的行数（从0开始，共读取6行，则设为5）
        List<Map<String,Object>> list = ExcelImportUtil.importExcel(
                file.getInputStream(),
                Map.class,
                params
        );
        for (Map<String, Object> map : list) {
            String kpi = map.get("科目").toString();
            switch (kpi){
                case "主营业务收入":
                    handleImport(year,companyId,map,pfIncomeMapper);
                    break;
                case "主营业务成本":
                    handleImport(year,companyId,map,pfCostMapper);
                    break;
                case "费用":
                    handleImport(year,companyId,map,pfExpenseMapper);
                    break;
                case "利润":
                    handleImport(year,companyId,map,pfProfitMapper);
                    break;
                case "合同":
                    handleImport(year,companyId,map,pfOrderMapper);
                    break;
                default://回款
                    handleImport(year,companyId,map,pfSalesBackMapper);
                    break;
            }
        }
        return null;
    }

    /**
     * 导出预算excel
     *
     * @param servletResponse
     * @param year
     * @param companyId
     */
    @Override
    public void exportBudget(HttpServletResponse servletResponse, String year, String companyId) {
        TemplateExportParams params = new TemplateExportParams(ExcelUtils.convertTemplatePath("excelTemplates/budgetModel.xlsx"), true);
        // 数据模板
        Map<String, Object> data = new HashMap<String, Object>();
        // 填充月份
        data.put("year",year);
        //支出情况
        List<Map> budgetList = getBudgetByYear(year,companyId);
        data.put("budgetList",budgetList);
        try {
            ExcelUtils.exportExcelByTemplate(params,data,year+"年预算报表.xlsx",servletResponse);
            System.out.println("导出成功");
        } catch (Exception e) {
            System.out.println("导出Excel，失败:" + e);
        }
    }

    public void handleImport(String year,String companyId, Map<String,Object> map, CompositeViewMapper mapper){
        for(String key:map.keySet()){
            if(key.endsWith("月")){
                Integer month = Integer.parseInt(key.split("月")[0]);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Date monthDate = null;
                try {
                        monthDate = sdf.parse(year+"-"+(month>10?month:""+month)+"-01");
                        Map<String,Object> param = new HashMap<>();
                        param.put("companyId",companyId);
                        param.put("monthDate",monthDate);
                        param.put("budget",map.get(key)==null?"0":map.get(key));
                        mapper.importBudgets(param);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
